package com.ljc.cjgl.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


@Service
public class SysUserService implements UserDetailsService{
	@Autowired
	private SysUserRepository sysUserDAO;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser user = sysUserDAO.findByUsername(username);
		if(user==null) {
			throw new UsernameNotFoundException(username);
		}
		List<SysRole> roles = user.getRoles();
		List<GrantedAuthority> authorities=new ArrayList<>();
		for (SysRole role : roles) {
			authorities.add(new SimpleGrantedAuthority(role.getCode()));
		}
        return new User2(user.getUsername(), user.getPassword(),user.getName(), authorities);
	}

	public void save(SysUser user) {
		sysUserDAO.save(user);
		
	}
	
}
